<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by index.php
 * Date: 29.11.13
 * User: Lesh
 */

class Controller_Site_Index extends Controller_Site
{

	public function action_index()
	{
		$this->template->content = new View('site/index/index');

		$errors = array();
		$images_model = ORM::factory('image')->reset(false);

		$page_count = $images_model->count_all();
		$page = $this->page($this->request->param('page'));

		$images = $images_model->view_images($page['limit'], $page['offset']);

		if ($this->request->method() === Request::POST)
		{
			$image = ORM::factory('image')->values(Arr::merge($_FILES, $this->request->post()));
			try
			{
				$image->save();
				if ($this->request->param('page'))
				{
					$this->request->redirect(Route::url('site-index', array('page' => $this->request->param('page'))));
				}
				$this->request->redirect(Route::url('site-index'));
			}
			catch (ORM_Validation_Exception  $e)
			{
				$errors = $e->errors('upload');
				$errors = Arr::merge($errors, Arr::get($errors, '_external', array()));
				unset($errors['_external']);
			}
		}

		$this->template->title = 'Главная';
		$this->template->script = View::factory(
				'site/index/script',
				array(
					 'page_count' => $page_count,
					 'page' => $page['page'],
					 'page_item' => $page['limit']
				)
			)->render();

		$this->template->content->images = $images;
		$this->template->content->content = View::factory(
				'site/index/content',
				array(
					 'images' => $images,
					 'page' => $page['page']
				)
			)->render();
		$this->template->content->errors = $errors;
	}
}